<?php
class lib_imageMark
{
    private $_transparent = 30;

    public function __construct($transparent = 30)
    {
        $this->_transparent = $transparent;
    }
    
    public function set_transparent($n)
    {
        $this->_transparent = (int)$n;
        return ;
    }
    
    public function mark($src , $mark , $dest , $x_percent = 100 , $y_percent = 100)
    {
    	if(!is_file($mark) || !is_file($src))
            return false;
            
        $mark_size = getimagesize($mark);
        $mark_w = $mark_size[0];
        $mark_h = $mark_size[1];
        $mark_mime = $mark_size['mime'];
            
        $img_size = getimagesize($src);
        $width = $img_size[0];
        $height = $img_size[1];
        $mime = $img_size['mime'];
        
        //比水印还小，退出
        if($mark_w > $width || $mark_h > $height)
        {
            if(!$src <> $dest)
                copy($src , $dest);
                
            return true;
        }
        
        //水印起始坐标
        $merge_x = ceil(($width - $mark_w) * ($x_percent/100));
        $merge_y = ceil(($height - $mark_h) * ($y_percent/100));
        
        if(class_exists('Imagick'))
        	$this->_mark_imagick($src , $mark , $dest ,$merge_x , $merge_y);
        else 
        	$this->_mark_gd($src , $mark , $dest , $mime , $mark_mime , $merge_x , $merge_y);
        
    }
    
    public function _mark_gd($src ,$mark, $dest , $mime , $mark_mime ,$x , $y)
    {
        if ($mime == 'image/jpeg')
            $pic_handle = imagecreatefromjpeg($src);
        else if ($mime == 'image/gif')
            $pic_handle = imagecreatefromgif($src);
        else if ($mime == 'image/png')
            $pic_handle = imagecreatefrompng($src);
            
        if ($mark_mime == 'image/jpeg')
            $mark_handle = imagecreatefromjpeg($mark);
        else if ($mark_mime == 'image/gif')
            $mark_handle = imagecreatefromgif($mark);
        else if ($mark_mime == 'image/png')
            $mark_handle = imagecreatefrompng($mark);
            
        
        
        imagecopymerge($pic_handle, $mark_handle, $merge_x, $merge_y, 0, 0, $mark_w, $mark_h , $this->_transparent);
        
        if ($mime == 'image/jpeg')
            imagejpeg($pic_handle , $dest , 100);
        else if ($mime == 'image/gif')
            imagegif($pic_handle , $dest , 100);
        else if ($mime == 'image/png')
            imagepng($pic_handle , $dest , 100);
            
        return true;
    }
    
    private function _mark_imagick($src , $mark , $dest , $x , $y)
    {
    	$srcPic = new Imagick($src);
		$srcPic->setImageCompression(Imagick::COMPRESSION_JPEG);   
		$srcPic->setImageCompressionQuality(100);    //设置图片的压缩质量   1-100 如果这里的值设成90, 200多k的图片 会大几十k
		
		//水印文件选择
		$water = new Imagick($mark);

		$srcPic->compositeImage($water, Imagick::COMPOSITE_OVER, $x, $y);
		$srcPic->writeImage($dest);
		$srcPic->clear();
    }
    
}


?>